package com.dxh.service;

import com.dxh.handler.UserServiceHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Service;

/**
 * @Author: Dengxh
 * @Date: 2021/1/17 17:16
 * @Description:
 */
@Service
public class UserServiceImpl implements IUserService{
    //将来客户端要远程调用的方法
    public String sayHello(String msg) {
        System.out.println("调用成功参数："+ msg);
        return "调用成功--参数 "+msg;
    }

    //创建一个方法，启动服务
    public static void startServer(String ip,int port) throws InterruptedException {
        //创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        //创建服务端启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //配置启动引导对象
        serverBootstrap.group(bossGroup, workGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel ch)  throws Exception {
                            //获取管道对象
                            ChannelPipeline pipeline = ch.pipeline();
                            //给管道对象设置编码
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                            //把自定义ChannelHander添加到通道中
                            pipeline.addLast(new UserServiceHandler());
                        }
                    });
        //绑定端口
        serverBootstrap.bind(ip,port).sync();
    }
}
